//
//  HDBmobFramework.m
//  Food
//
//  Created by 包月兴 on 2018/7/25.
//  Copyright © 2018年 包月兴. All rights reserved.
//

#import "HDBmobFramework.h"
#import "HDFCategoryObject.h"
#import "HDFFoodObject.h"
#import "HDSellerObject.h"
#import <BmobSDK/Bmob.h>
#import <NSString+EncryptSha.h>
#import "HDAccount.h"
#import "HDAddressObject.h"
#import "MQLFoodModel.h"
#import "HDOrderObject.h"
#import <NSTimer+YZBlcokSupport.h>
@implementation HDBmobFramework

-(instancetype)init
{
    if (self =[super init]) {
        _formatter = [[NSDateFormatter alloc] init];
        [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return self;
}
SingletonM


-(void)updateServiceData
{
    [self p_updateServiceSellerData];
    [self p_updateServiceFoodDataWithComplete:^(NSError * _Nullable error) {
          [self p_updateServiceCategoryData];
    }];
    if (![[HDAccount account].userID isEqualToString:@""] && [HDAccount account].userID) {
        [self downOrderlist];
        if ([HDAccount account].isAdmin) {
            [NSTimer scheduledTimerWithTimeInterval:4 block:^{
                [self downOrderlist];
            } repeats:YES];
        }
    }
}





-(void)loginWithName:(NSString *)name pwd:(NSString *)pwd complete:(void (^)(NSError * _Nullable))complete
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"_User"];
    [bquery whereKey:@"username" equalTo:name];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (array.count == 0) {
             //注册
            BmobObject *user = [BmobObject objectWithClassName:@"_User"];
            [user setObject:name forKey:@"username"];
            [user setObject:[[pwd md5] encryptSha256] forKey:@"password"];
            [user setObject:@(NO) forKey:@"isAdmin"];
            [user saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                if (error) {
                    if (complete) {
                        complete(error);
                    }
                    return;
                }
                [self loginWithName:name pwd:pwd complete:complete];
            }];
        }else
        {
            //登录
            [BmobUser loginWithUsernameInBackground:name password:[[pwd md5] encryptSha256] block:^(BmobUser *user, NSError *error) {
                if (error) {
                    if (complete) {
                        complete(error);
                    }
                    return;
                }
                [self p_updateServiceAddressData];
                BOOL isAdmin = [[user objectForKey:@"isAdmin"] boolValue];
                HDAccount *account = [HDAccount accountWithDic:@{@"uid":user.objectId,@"isAdmin":@(isAdmin)}];
                [HDAccount save:account];
                [self downOrderlist];
                if ([HDAccount account].isAdmin) {
                    [NSTimer scheduledTimerWithTimeInterval:4 block:^{
                        [self downOrderlist];
                    } repeats:YES];
                }
                if (complete) {
                    complete(nil);
                }
            }];
            
        }
    }];
}


#pragma mark ---  新增收货地址

-(void)addAddressWithRealName:(NSString *)realName mobile:(NSString *)mobile detailAddress:(NSString *)detailAddress complete:(void (^)(NSError * _Nullable))complete
{
       BmobObject *address = [BmobObject objectWithClassName:@"Address"];
       [address setObject:realName forKey:@"ralname"];
       [address setObject:mobile forKey:@"mobile"];
       [address setObject:detailAddress forKey:@"detail"];
       BmobUser *user = [BmobUser currentUser];
        [address setObject:user forKey:@"user"];
    [address saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (!isSuccessful) {
            if (complete) {
                complete(error);
            }
            return;
        }
        [self p_updateServiceAddressData];
        if (complete) {
            complete(nil);
        }
    }];
}

-(void)deleteAddressWithObjectId:(NSString *)objectId complete:(void (^)(NSError * _Nullable))complete
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"Address"];
    [bquery getObjectInBackgroundWithId:objectId block:^(BmobObject *object, NSError *error) {
        if (complete) {
            complete(error);
            return;
        }
        if (object) {
            [object deleteInBackground];
        }
        [HDAddressObject deleteAddressObjectWithObjectId:objectId];
    }];
}

#pragma mark ---  下订单

-(void)placeOrderWithFoodList:(NSArray<MQLFoodModel *> *)foodList amount:(double)amount addressObject:(nonnull HDAddressObject *)addressObject remark:(nonnull NSString *)remark complete:(nonnull void (^)(NSError * _Nullable))complete
{
      BmobObject *order = [BmobObject objectWithClassName:@"Order"];
      BmobUser *user = [BmobUser currentUser];
      [order setObject:user forKey:@"user"];
    //  [order setObject:foodList forKey:@"detail"];
    NSMutableArray *arr = [NSMutableArray array];
    for (MQLFoodModel *model in foodList) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:model.objectId forKey:@"objectId"];
        [dic setObject:model.name forKey:@"name"];
        [dic setObject:model.imgUrl forKey:@"imgUrl"];
        [dic setObject:@(model.price) forKey:@"price"];
        [dic setObject:@(model.buyCount) forKey:@"buyCount"];
        [arr addObject:dic];
    }
     [order setObject:arr forKey:@"detail"];
      [order setObject:@(amount) forKey:@"amount"];
      [order setObject:remark forKey:@"remark"];
      [order setObject:@(1) forKey:@"payType"];
      [order setObject:@(1) forKey:@"sendType"];
   // BmobObject *address = [BmobObject objectWithoutDataWithClassName:@"Address" objectId:addressObject.objectId];
    NSDictionary *address = @{@"realName":addressObject.realName,@"mobile":addressObject.mobile,@"detailAddress":addressObject.detailAddress};
    
    [order setObject:address forKey:@"address"];
    [order setObject:@(HDOrderStatusNoVerify) forKey:@"state"];
    [order saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        if (error) {
            if (complete) {
                complete(error);
            }
            return;
        }
        [self downOrderlist];
        if (complete) {
            complete(nil);
        }
        
    }];
}

#pragma mark ---  商家确认订单

-(void)confirmOrderWithObjectId:(NSString *)objectId complete:(void (^)(NSError * _Nullable))complete
{
     BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Order"];
    [bquery getObjectInBackgroundWithId:objectId block:^(BmobObject *object, NSError *error) {
        if (!error) {
            if (object) {
                [object setObject:@(HDOrderStatusVerify) forKey:@"state"];
                [object updateInBackground];
                [HDOrderObject confirmOrderWithObjectId:objectId complete:^(NSError * _Nullable error) {
                    
                }];
            }
        }
    }];
}



-(void)p_updateServiceCategoryData
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Category"];
    NSDate *updatedAt = [HDFCategoryObject getNewUpdatedAt];
    if (updatedAt) {
       [bquery whereKey:@"updatedAt" greaterThan:updatedAt];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            return ;
        }
        [HDFCategoryObject insertDataWithBmobObjectLists:array complete:^(NSError * _Nullable error) {
            
        }];
        
    }];
}



-(void)p_updateServiceFoodDataWithComplete:(void (^)(NSError * _Nullable error))complete
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Food"];
    NSDate *updatedAt = [HDFCategoryObject getNewUpdatedAt];
    if (updatedAt) {
        [bquery whereKey:@"updatedAt" greaterThan:updatedAt];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            return ;
        }
        [HDFFoodObject insertDataWithBmobObjectLists:array complete:^(NSError * _Nullable error) {
            if (complete) {
                complete(nil);
            }
        }];
    }];
}


-(void)p_updateServiceSellerData
{
     BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Seller"];
     NSDate *updatedAt = [HDSellerObject getNewUpdatedAt];
    if (updatedAt) {
         [bquery whereKey:@"updatedAt" greaterThan:updatedAt];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            return ;
        }
        [HDSellerObject insertDataWithBmobObjectLists:array complete:^(NSError * _Nullable error) {
            
        }];
    }];
}

-(void)p_updateServiceAddressData
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Address"];
     BmobUser *user = [BmobUser currentUser];
    if (![HDAccount account].isAdmin) {
         [bquery whereKey:@"user" equalTo:user];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            return ;
        }
        [HDAddressObject insertDataWithBmobObjectLists:array complete:^(NSError * _Nullable error) {
            
        }];
        
    }];
}

-(void)downOrderlist
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"Order"];
    NSDate *updatedAt = [HDOrderObject getNewUpdatedAt];
    if (updatedAt) {
        [bquery whereKey:@"updatedAt" greaterThan:updatedAt];
    }
    BmobUser *user = [BmobUser currentUser];
    if (![HDAccount account].isAdmin) {
         [bquery whereKey:@"user" equalTo:user];
    }
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error) {
            return ;
        }
        [HDOrderObject insertDataWithBmobObjectLists:array complete:^(NSError * _Nullable error) {
            
        }];
        
    }];
    
}



@end
